/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Net.Client;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author Administrator
 */

 

public class ClientSocket {
    private String ip;

    private int port;

    private Socket socket,temp = null;

    DataOutputStream out= null;

    DataInputStream inputStream = null;
    boolean isLive=true;
    int percent ;
    public ClientSocket(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    /** *//**
     * 创建socket连接
     * 
     * @throws Exception
     *             exception
     */
    public void CreateConnection() throws Exception {
        try {
            
            socket = new Socket(ip, port);
             out = new DataOutputStream(socket.getOutputStream());
             inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
        } catch (Exception e) {
            e.printStackTrace();
            if (socket != null)
                socket.close();
            throw e;
        } finally {
        }
    }

    public void sendMessage(String sendMessage) throws Exception {
        try {
           
            if (sendMessage.equals("Windows")) {
                out.writeByte(0x1);
                out.flush();
                return;
            }
            if (sendMessage.equals("Unix")) {
                out.writeByte(0x2);
                out.flush();
                return;
            }
            if (sendMessage.equals("Linux")) {
                out.writeByte(0x3);
                out.flush();
            } else {
                out.writeUTF(sendMessage);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (out != null)
                out.close();
            throw e;
        } finally {
        }
    }

    public DataInputStream getMessageStream() throws Exception {
        try {
            
            return inputStream;
        } catch (Exception e) {
            e.printStackTrace();
            if (inputStream != null)
                inputStream.close();
            throw e;
        } finally {
        }
    }

    public void shutDownConnection() {
        try {
            if (out != null)
                out.close();
            if (inputStream != null)
                inputStream.close();
            if (socket != null)
                socket.close();
        } catch (Exception e) {

        }
    }


   public void downLoad() {
         reConnect("下载方法里面");            
         try {  out.writeByte(0x1);
                out.flush();
            //本地保存路径，文件名会自动从服务器端继承而来。
            String savePath = "E:\\";
            int bufferSize = 8192;
            byte[] buf = new byte[bufferSize];
            int passedlen = 0;
            long len=0;
            
            savePath += inputStream.readUTF();
            DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
            len = inputStream.readLong();
            
            System.out.println("文件的长度为:" + len + "\n");
            System.out.println("开始接收文件!" + "\n");
                    
            while (true) {
                int read = 0;
                if (inputStream != null) {
                    read = inputStream.read(buf);
                }
                passedlen += read;
                if (read == -1) {
                    break;
                }
                //下面进度条本为图形界面的prograssBar做的，这里如果是打文件，可能会重复打印出一些相同的百分比
                System.out.println("文件接收了" +  (passedlen * 100/ len) + "%\n");
                setPercent((passedlen * 100/ len));
                fileOut.write(buf, 0, read);
            }
            System.out.println("接收完成，文件存为" + savePath + "\n");

            fileOut.close();
            close();
        } catch (Exception e) {
            System.out.println("接收消息错误" + "\n");
            return;
        }
    }
public void  UpLoad(String filePath)throws Exception{
      reConnect("上传方法里面");
      try {
         File fi = new File(filePath);
            
                System.out.println("文件长度:" + (int) fi.length());
               // DataInputStream dis = new DataInputStream(new BufferedInputStream(inputStream));
                inputStream.readByte();
                DataOutputStream ps = new DataOutputStream(out);
               
               
             
                DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
                //将文件名及长度传给客户端。这里要真正适用所有平台，例如中文名的处理，还需要加工，具体可以参见Think In Java 4th里有现成的代码。
                ps.writeUTF("text.txt");
                ps.flush();
                ps.writeLong((long) fi.length());
                ps.flush();

                int bufferSize = 8192;
                byte[] buf = new byte[bufferSize];

                while (true) {
                    int read = 0;
                    if (fis != null) {
                        read = fis.read(buf);
                    }

                    if (read == -1) {
                        break;
                    }
                    ps.write(buf, 0, read);
                }
                ps.flush();
                // 注意关闭socket链接哦，不然客户端会等待server的数据过来，
                // 直到socket超时，导致数据不完整。                
                fis.close();
                 } catch (Exception e) {
            e.printStackTrace();
        }
      close();
      
    }
    OutputStream getOutputStream() throws IOException {
        return out;
    }

    void close() throws IOException {
      try {
    socket.close();
    isLive =false;
   } catch (Exception ei) {
    ei.printStackTrace();
   }
    }

 public   void write(String str) throws IOException  {
       reConnect("write里面的");
        out.writeUTF(str);
    }
 public String read() throws IOException{
    
     reConnect("read 方法里面");
      return   inputStream.readUTF();
    
 }
 private void reConnect(String str){
      try{if(!isLive){
                 socket=new Socket(ip,port);  System.out.println("重新建立连接"+str);
            out = new DataOutputStream(socket.getOutputStream());
            inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            isLive = true ;
            }
        } catch (Exception ex) {
           
        }
 }
 private void setPercent(double n){
       percent=(int)n;
 }
 public  int getPercent(){
     return percent ;
 }
}
    

